package com.hksj.app.websocket;

import com.alibaba.fastjson.JSONObject;
import com.hksj.common.core.model.Rest;
import com.hksj.app.websocket.message.Subscription;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import java.util.HashMap;
import java.util.Map;

@Component
public class ApiAdapter {
    @Autowired
    private RequestMappingHandlerMapping handlerMapping;
    @Autowired
    private ApplicationContext applicationContext;

    Map<String, HandlerMethod> handlerMethodMap = new HashMap<>();

    public Object invoke(Subscription subscription){
        if (ObjectUtils.isEmpty(handlerMethodMap)){
            for (RequestMappingInfo requestMappingInfo : handlerMapping.getHandlerMethods().keySet()) {
                for (String path : requestMappingInfo.getPatternValues()) {
                    handlerMethodMap.put(path,handlerMapping.getHandlerMethods().get(requestMappingInfo));
                }
            }
        }
        Object res = null;
        try {
            HandlerMethod handlerMethod = handlerMethodMap.get(subscription.getUrl());
            Object bean = applicationContext.getBean(handlerMethod.getBean().toString());
            Object param = JSONObject.parseObject(subscription.getParams(), handlerMethod.getMethod().getParameterTypes()[0]);
            res = handlerMethod.getMethod().invoke(bean, param);
            if (res instanceof Rest){
                res = ((Rest<?>) res).getData();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return res;
    }

    public ApplicationContext getApplicationContext() {
        return applicationContext;
    }
}
